<template>
  <div class="app-container">

    <div class="head-container flex-center position-sticky" style="border-bottom: 1px solid #ddd;">
      <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>审批流程定义</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div style="text-align: right">
        <el-button type="success"
                   plain
                   size="small"
                   @click="saveProcess">保存流程
        </el-button>
        <el-button type="primary"
                   plain
                   size="small"
                   @click="previewProcess">预览流程
        </el-button>
        <el-button type="danger"
                   plain
                   size="small">重置数据
        </el-button>
      </div>
    </div>

    <div class="body-container">
      <el-row :gutter="20">
        <el-col :span="18" :xs="24">
          <el-timeline class="clear-padding">
            <el-timeline-item v-for="(item, index) in form.nodes"
                              :timestamp="`【${item.flow}】${item.label}`"
                              :key="index"
                              size="large"
                              :color="theme"
                              placement="top">
              <div v-if="index === 0"
                   class="mb5 flex-center"
                   :style="{color: theme, fontSize: '13px'}">
                <el-tag type="info">首节点为默认节点，无法进行编辑、删除操作</el-tag>
                <el-button type="primary"
                           plain
                           size="mini"
                           @click="insertNode">新增节点</el-button>
              </div>
              <el-card shadow="none">
                <div>
                  <el-tooltip placement="top" effect="light" content="[会签]当前节点的所有审批人员全部通过审批后才能进入下一节点；[或签]当前节点的任一审批人员通过审批后即可进入下一节点。">
                    <el-tag :type="item.mode === '1' ? 'danger' : 'success'">{{selectDictLabel(modeOptions, item.mode)}}</el-tag>
                  </el-tooltip>
                  <el-tag class="ml0">审批人员</el-tag>
                  <el-tag type="warning"
                          v-if="!item.examinerId.length"
                          class="ml0">
                    <span>当前节点暂无审批人员</span>
                  </el-tag>
                  <el-tag v-else
                          v-for="user in item.examinerId"
                          :closable="index !== 0"
                          type="warning"
                          class="ml0"
                          :key="user._id"
                          @close="handleClose(user, index)">{{examinerDetail(user)}}</el-tag>
                  <div class="fr">
                    <el-button type="success"
                               v-if="index !== 0"
                               plain
                               size="mini"
                               @click="openUserDialog(index)">添加审批人员</el-button>
                    <el-button type="primary"
                               plain
                               size="mini"
                               v-if="index !== 0"
                               @click="editNodeInfo(item, index)">编辑</el-button>
                    <el-button type="danger"
                               plain
                               size="mini"
                               v-if="index !== 0"
                               @click="deleteNode(item)">删除</el-button>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-col>
        <el-col :span="6"
                class="position-sticky"
                style="top: 63px;"
                :xs="24">
          <el-form :model="form"
                   ref="form"
                   :rules="formRules"
                   label-width="120px">
            <el-form-item label="审批流名称：" prop="name">
              <el-input v-model="form.name"
                        placeholder="请输入审批流名称" />
            </el-form-item>
            <el-form-item label="审批流编码：" prop="code">
              <el-input v-model="form.code"
                        placeholder="请输入审批流编码" />
            </el-form-item>
            <el-form-item label="审批流状态：" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">正常</el-radio>
                <el-radio label="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea"
                        v-model="form.remark"
                        placeholder="请输入备注" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <el-dialog title="选择审批人员"
               width="60%"
               :close-on-click-modal="false"
               top="25vh"
               :visible.sync="examinerDialog">
      <el-row :gutter="10">
        <el-col :span="6" :xs="24">
          <el-tree :data="deptOptions"
                   :props="defaultProps"
                   node-key="deptCode"
                   highlight-current
                   :expand-on-click-node="false"
                   ref="tree"
                   default-expand-all
                   @node-click="handleNodeClick"/>
        </el-col>
        <el-col :span="18" :xs="24">
          <el-input v-model="queryParams.keywords"
                    style="width: 240px"
                    class="mb10"
                    clearable
                    prefix-icon="el-icon-search"
                    placeholder="请输入审批人姓名搜索"
                    @input="handleQuery" />
          <el-button type="primary"
                     plain
                     class="fr"
                     @click="confirmSelect">确认选择</el-button>
          <el-table :data="userList"
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </el-table-column>
            <el-table-column type="selection"
                             width="55"/>
            <el-table-column label="用户编号"
                             width="140"
                             prop="username"/>
            <el-table-column label="用户名称"
                             prop="nickname"
                             width="140"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="所属部门"
                             prop="dept.deptName"
                             width="150"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="手机号码"
                             prop="phone"
                             width="150"/>
            <el-table-column label="邮箱"
                             prop="email" />
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getUserList"
          />
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :title="nodeInfoDialogTitle"
               width="500px"
               :close-on-click-modal="false"
               :visible.sync="editNodeInfoDialog">
      <el-form :model="nodeForm"
               label-width="120px"
               :rules="nodeFormRules"
               ref="nodeForm">
        <el-form-item label="节点名称：" prop="label">
          <el-input v-model="nodeForm.label"
                    placeholder="请输入节点名称"
                    clearable />
        </el-form-item>
        <el-form-item label="流程状态值：" prop="flow">
          <el-input v-model="nodeForm.flow"
                    placeholder="请输入流程状态值"
                    clearable />
        </el-form-item>
        <el-form-item label="审批模式：" prop="mode">
          <Select :options="modeOptions"
                  v-model="nodeForm.mode"
                  clearable
                  style="width: 100%;"
                  placeholder="请选择当前节点审批模式" />
        </el-form-item>
        <el-form-item label="审批人员：" prop="examinerName">
          <el-input v-model="nodeForm.examinerName"
                    placeholder="请选择审批人员"
                    @focus="openUserDialog('')"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary"
                   plain
                   @click="confirmEditNode">确 认</el-button>
        <el-button type="default"
                   plain
                   @click="editNodeInfoDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="预览流程"
               width="70%"
               :visible.sync="previewProcessDialog">
      <process-detail :data="form.nodes" :user-list="userList"></process-detail>
    </el-dialog>

  </div>
</template>

<script>
  import Select from '@/components/form/Select'
  import ProcessDetail from '@/components/ProcessDetail'
  import { listUser} from "@/api/system/user"
  import { listDept } from "@/api/system/dept"
  import { addProcess, detailProcess, updateProcess } from "@/api/system/process"

  export default {
    name: "Definition",
    components: { Select, ProcessDetail },
    data() {
      return {
        // 流程编码
        code: '',
        // 表单参数
        form: {},
        // 审核模式下拉选项
        modeOptions: [],
        // 审批人弹框
        examinerDialog: false,
        // 用户列表
        userList: [],
        // 总数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keywords: undefined,
          status: '1',
        },
        // 部门树选项
        deptOptions: undefined,
        // 部门树默认配置
        defaultProps: {
          children: "children",
          label: "deptName"
        },
        // 当前填写的审批节点索引
        currentNodeIndex: 0,
        // 选中审批人的数组
        examinerSelected: [],
        // 编辑节点信息弹框
        editNodeInfoDialog: false,
        // 当前节点信息
        nodeForm: {},
        // 校验规则
        formRules: {
          code: [
            {required: true, message: '审批流编码不能为空', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '审批流名称不能为空', trigger: 'blur'}
          ]
        },
        // 节点信息弹框标题
        nodeInfoDialogTitle: '新增节点',
        // 节点信息表单校验
        nodeFormRules: {
          label: [
            {required: true, message: '点名称不能为空', trigger: 'blur'}
          ],
          flow: [
            {required: true, message: '流程状态值不能为空', trigger: 'blur'}
          ],
          mode: [
            {required: true, message: '审批模式不能为空', trigger: 'change'}
          ]
        },
        // 预览流程弹框
        previewProcessDialog: false
      }
    },
    computed: {
      // 主题色
      theme() {
        return this.$store.state.settings.theme;
      },
      // 根据id查询用户列表中的用户
      examinerDetail() {
        return id => {
          const user = this.userList.find(v => v._id === id)
          if (user && user.nickname) return user.nickname
          else return '未查找到该用户！'
        }
      },
    },
    created() {
      // 字典查询
      this.getDicts("sys_audit_mode").then(response => {
        this.modeOptions = response.data
      })
      this.reset()
      this.getUserList()
      this.getTreeSelect()
      this.code = this.$route.query && this.$route.query.code
      this.queryProcessByCode()
    },
    methods: {
      /** 查询审批流详情 */
      queryProcessByCode() {
        if (this.code) {
          detailProcess(this.code).then(res => {
            this.form = res.data
          })
        }
      },
      /** 表单重置 */
      reset() {
        const userId = this.$store.state.user.userId
        this.form = {
          code: undefined,
          nickname: undefined,
          status: '1',
          nodes: [
            {
              label: '提交审批',
              flow: '0',
              mode: '1',
              examinerId: [userId],
              examinerName: ''
            }
          ]
        }
        this.resetForm("form")
      },
      /** 新增节点 */
      insertNode() {
        this.nodeInfoDialogTitle = '新增节点'
        this.editNodeInfoDialog = true
        this.nodeForm = {
          label: undefined,
          flow: undefined,
          examinerId: [],
        }
        this.resetForm('nodeForm')
      },
      /** 删除节点 */
      deleteNode(item) {
        const index = this.form.nodes.indexOf(item)
        if (index !== -1) this.form.nodes.splice(index, 1)
      },
      /** 选择审批人弹框 */
      openUserDialog(index) {
        this.currentNodeIndex = index
        this.examinerDialog = true
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getUserList()
      },
      /** 查询用户列表 */
      getUserList() {
        this.loading = true
        listUser(this.queryParams).then(response => {
            this.userList = response.rows
            this.total = response.total
          }
        )
      },
      /** 节点单击事件 */
      handleNodeClick(data) {
        this.queryParams.deptCode = data.deptCode
        this.getUserList()
      },
      /** 选择审批人*/
      handleSelectionChange(selections) {
        this.examinerSelected = selections
      },
      /** 确认选择按钮*/
      confirmSelect() {
        if (this.examinerSelected && this.examinerSelected.length) {
          if (this.currentNodeIndex) {
            this.form.nodes[this.currentNodeIndex].examinerId = this.examinerSelected.map(item => item._id)
            this.form.nodes[this.currentNodeIndex].examinerName = this.examinerSelected.map(item => item.nickname).join('，')
          } else {
            this.nodeForm.examinerId = this.examinerSelected.map(item => item._id)
            this.nodeForm.examinerName = this.examinerSelected.map(item => item.nickname).join('，')
          }
        }
        this.examinerDialog = false
      },
      /** 移除审批人员 */
      handleClose(tag, index) {
        const target = this.form.nodes[index].examinerId.indexOf(tag)
        if (target !== -1) this.form.nodes[index].examinerId.splice(target, 1)
      },
      /** 查询部门下拉树结构 */
      getTreeSelect() {
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, 'deptCode', 'parentCode')
        })
      },
      /** 点击编辑按钮编辑节点信息 */
      editNodeInfo(item, index) {
        this.nodeInfoDialogTitle = '编辑节点'
        this.currentNodeIndex = index
        this.nodeForm = {...item}
        this.editNodeInfoDialog = true
      },
      /** 保存节点信息 */
      confirmEditNode() {
        this.$refs.nodeForm.validate(valid => {
          if (valid) {
            if (this.nodeInfoDialogTitle === '编辑节点') {
              this.form.nodes[this.currentNodeIndex].label = this.nodeForm.label
              this.form.nodes[this.currentNodeIndex].flow = this.nodeForm.flow
              this.form.nodes[this.currentNodeIndex].mode = this.nodeForm.mode
              this.editNodeInfoDialog = false
            } else {
              this.form.nodes.push({...this.nodeForm})
              this.editNodeInfoDialog = false
            }
          }
        })
      },
      /** 保存审批流 */
      saveProcess() {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form._id) {
              updateProcess(this.form).then(res => {
                this.msgSuccess('保存成功')
              })
            } else {
              addProcess(this.form).then(res => {
                this.msgSuccess('添加成功')
              })
            }
          }
        })
      },
      /** 预览流程 */
      previewProcess() {
        this.previewProcessDialog = true
      }
    }
  }
</script>

<style lang="scss">
  .queryForm {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
</style>
